import axios from 'axios';
import utils from './utils.js';
import {webHost, clientID, tokenUri,initDictionaryList } from './api';



export const funAxios = function (method,url,param,contentType,async){

    // 初始化字典
    if(!sessionStorage.allDictData||sessionStorage.allDictData=='[]'||sessionStorage.allDictData=='undefined'||utils.isEmpty(sessionStorage.allDictData)||utils.isEmpty(JSON.parse(sessionStorage.allDictData))){
        let params2 = {
            data:{isPageAble: false},
            access_token:"?access_token="+localStorage.token
        }
        initDictionaryList(params2).then(res=>{
            sessionStorage.allDictData = JSON.stringify(res.data.data.list) ;
        }).catch(err=>{
            console.log(err);
        });
    }

    var reqParamuilder = {url:url+"?access_token="+localStorage.token
        ,method:method
        ,data:param
        ,headers: {'Authorization': 'Bearer '+localStorage.token,'token':localStorage.token}}
    if(contentType&&contentType.length>5){
        reqParamuilder.dataType=contentType;
    }

    console.log("------------------------------------- "+localStorage.token)
    if(async==false){
        // todo 请勿使用同步请求
        $.ajax({ url: reqParamuilder.url, context: reqParamuilder.data, success: function(res){
                console.log(" 功能未完成，请无勿使用同步请求 ?????????????????????????????? ");
                console.log(res);
            }});
    }else {
        return axios(reqParamuilder).then(function(res){
            if (res && res.status=='200' ) {
                //如果token，基本那么就返回200：
                console.log(res);
                if(res.data.code=="SZUUL100506"){// 服务未连接, 请稍后再试
                    console.log("服务未连接, 请稍后再试 todo ");
                    goLoginPage();
                }
                return res;
            }
        }).catch(err=>{
            if (err && err.response && err.response.status ) {
                console.log(err)
                console.log(err.response)
                console.log(err.response.data)
                console.log(err.response.status)
                console.log("尝试刷新token");
                if(err.response.status>=400&&err.response.status<=499 && err.response.status!=404 /*&& err.response.data.error == "invalid_token"*/){
                    // 尝试刷新token 失败后跳登录页面
                    reTryNum=0;
                    return goReFershToken(method,url,param,contentType);
                }else{
                    throwUnknownERR(err,"系统异常：");
                }
            }else if(err.message){
                console.log("网络错误：");
                console.log(err.message)
                console.log(err)
                reTryNum=0;
                return goReFershToken(method,url,param,contentType);
            }else{
                throwUnknownERR(err,"错误对象异常！");
            }
        });
    }
}



function goReFershToken(method,url,param,contentType) {
    return axios({
        url:tokenUri
        ,method:"POST"
        ,data:"grant_type=refresh_token&refresh_token="+localStorage.retoken
        ,headers: {'Authorization': 'Basic '+clientID,"Content-Type":"application/x-www-form-urlencoded"}// 'dGVzdDI6dGVzdDI=' test2:test2 ||  'd2ViOndlYg==' web:web
    }).then(function(res){
        if(res && res.status=='200'){
            localStorage.token = res.data.access_token
            localStorage.retoken = res.data.refresh_token
            console.log("刷新token成功，回调接口：method:"+method+" url:"+url+" param"+param);
            return funAxios(method,url,param,contentType);// 成功后回调原来的请求
        }else{ console.log("刷新token失败，但是没抛异常：");console.log(res);throw '请重新登录4';  }
    }).catch(err=>{// 有可能 retoken 过期，或者参数有误缺失
        console.log("刷新token失败");
        console.log(err.response.data)
        console.log(err);
        if((err.response.data&&err.response.status>=400&&err.response.status<=499&&err.response.status!=404)){
            goLoginPage();
        }else if(err.response.data&&err.response.status==500/*&&err.response.data.error_description&&err.response.data.error_description.indexOf("Jedis") != -1*/){//  redis access 数据被删除
            console.log(" 500 状态码，尝试重试 "+reTryNum)
            return reTryFershToken(method,url,param,contentType)
        }else{throwUnknownERR(err);}
    });
}


var reTryNum = 0;
var maxTryNum = 2
function reTryFershToken(method,url,param,contentType) {
    if(reTryNum<(maxTryNum-1)){
        reTryNum++;
        return goReFershToken(method,url,param,contentType);
    }else{
        reTryNum=0;
        goLoginPage();
    }
}

function goLoginPage() {
    console.log("跳转到重新登录页面");
    // _this.$router.push('/uam/login22')
    // parent.location.href=webHost+"/webos99/index.html";
    window.location.href=webHost+"/#/loginSecond";
}

function throwUnknownERR(err,msg) {
    if(!msg){msg="未知状态："}
    try{
        console.log(msg+""+err.response.status)
        console.log(err.response.data)
        console.log(err);
    }catch(err) {}
    throw err;
}






























// axioss: function (url,method,param,callback,failCallback){
//     var _this = this;
//     axios({url:url,method:method,data:param,headers: {'Authorization': 'Bearer '+localStorage.token}}).then(function(res){
//         if (res && res.status=='200' ) {
//             //判断token有没有失效，如果有：
//             console.log(res);
//             // callback(res);
//             return res;
//         }
//     }).catch(err=>{
//         if (err && err.response && err.response.status ) {
//             console.log(err)
//             console.log(err.response)
//             console.log(err.response.data)
//             console.log(err.response.status)
//             if(err.response.status == '401' && err.response.data.error == "invalid_token"){
//                 console.log("invalid_token");
//                 // 尝试刷新token 失败后跳登录页面
//                 axios({
//                     url:"http://localhost:8784/uaa/oauth/token"
//                     ,method:"POST"
//                     ,data:{"grant_type":"refresh_token","refresh_token":localStorage.retoken}
//                     ,headers: {'Authorization': 'Basic dGVzdDI6dGVzdDI='}//
//                 }).then(function(res){
//                     // {
//                     //     "access_token": "5c0631e5-4d9e-402e-9b83-d718b3220e5c",
//                     //     "token_type": "bearer",
//                     //     "refresh_token": "0550e40b-5212-43cb-af9e-0a6c519cee8b",
//                     //     "scope": "*"
//                     // }
//                     if(res && res.status=='200'){
//                         localStorage.token = res.data.access_token
//                         localStorage.retoken = res.data.refresh_token
//                     }else{ throw '请重新登录4';  }
//                 }).catch(err=>{// 有可能 retoken 过期，或者参数有误缺失
//                     console.log("刷新token失败，请重新登录3");
//                     console.log(err);
//                     alert("刷新token失败，请重新登录3");
//                 });
//             }else{
//                 // callback(err);
//                 console.log("未知状态："+err.response.status)
//                 console.log(err);
//                 throw err;
//             }
//         }else{
//             // callback(err);
//             console.log(err);
//             alert("找不到状态码，系统错误。请重新登录1");
//             throw err;
//         }
//     });
// },